const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()

/**根据手机号获得功德主信息和放生余额
 * 若手机号已存在直接返回，手机号不存在直接创建
 * **/
const findInfoByMobile = async (event) => {
  const mobile = event.mobile
  const queryResult = await db.collection("kindPersonInfo").where({mobile: mobile}).get({})
  const infoData = queryResult.data
  console.info('查询结果为： ',queryResult)
  if(infoData == undefined || infoData == null || infoData.length == 0){
    const info = { mobile: mobile, roles: '普通用户' }
    const insertResult = await db.collection('kindPersonInfo').add({data: info})
    if(insertResult._id){
      console.info('添加成功：'+insertResult)
      return {data: info,errmsg: '添加用户成功.'}
    }
    return {data: undefined, errMsg: '登录失败'}
  }
  let kindName = infoData[0].meritsVirtues
  if(kindName == undefined || kindName =='' || kindName == null){
    console.warn('查询成功，用户未绑定功德主名称.\n')
    return {data: infoData, errMsg: '未绑定功德主名称.'}
  }
  const queryFreeAmoResult = await db.collection('freeCaptiveDetails').where({ meritsVirtues: kindName}).orderBy('freeDate', 'desc').limit(1).get()
  let detailData = queryFreeAmoResult.data
  console.info('明细表查询结果：',detailData)
  console.info("集合查询结果为：",infoData)
  if(detailData.length == 0){
    console.warn('更据功德主(meritsVirtues)查询放生明细表结果为空，直接返回。')
    return {data: infoData, errMsg: '获取金额失败'}
  }
  for(let i=0; i < infoData.length; i++){
    infoData[i].balance = detailData[0].balance
  }
  return {data: infoData,errMsg: '请求成功.'}
}

/**
 * 
 * @param {reqType: 请求类型，必填,collectionName: 集合名称，必填 } event 
 */
const main = async (event) => {
  const reqType = event.reqType
  switch(reqType){
  /**更据功德主名查询功德主信息， */
    case 'findInfoByMobile':
      return await findInfoByMobile(event)
    default:
      return {data: undefined, errMsg: '请求类型不存在.'}
  }
}

module.exports = {
  main,
}